package com.crayfish.quduo.base;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by crayfish on 2016/12/2.
 */
public abstract class BaseFragment extends Fragment{

    private ProgressDialog progressDialog;
    protected View mView;
    protected Activity activity;
    protected Context mContext;
    private Unbinder unbinder;
    protected boolean isInit = false;

    @Override
    public void onAttach(Context context) {
        activity = (Activity)context;
        mContext = context;
        super.onAttach(context);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mView = inflater.inflate(getLayoutId(),null);
        return mView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        unbinder = ButterKnife.bind(this,view);
        if(savedInstanceState == null){
            if(!isHidden()){
                isInit = true;
                initEventAndData();
            }
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(!isInit && !hidden){
            isInit = true;
            initEventAndData();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    public void showProgress(String msg){
        if(progressDialog==null){
            progressDialog=new ProgressDialog(getActivity());
        }
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setMessage(msg);
        progressDialog.show();
    }

    public void showProgress(int res){
        if(progressDialog==null){
            progressDialog=new ProgressDialog(getActivity());
        }
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setMessage(getActivity().getResources().getString(res));
        progressDialog.show();
    }

    public void hideProgress(){
        if(progressDialog!=null&&progressDialog.isShowing()){
            progressDialog.dismiss();
        }
    }

    public void startMyActivity(Class clazz) {
        startActivity(new Intent(getActivity(), clazz));
    }

    protected abstract int getLayoutId();
    protected abstract void initEventAndData();
}
